package com.kuang.springcloud.utils;

import com.alibaba.fastjson.JSON;
import com.kuang.springcloud.pojo.Dept;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 模拟消息队列刷新服务
 */
public class RefreshServiceUtils {

    /**
     * 模拟消息队列刷新服务的重载函数
     * @param client DiscoveryClient
     * @param path 请求后缀路径
     * @param dept 请求的增量参数,在公司我使用的是List
     */
    public void refreshService(DiscoveryClient client, String path, Dept dept) {
        List<String> services = client.getServices();
        List<String> exceptServiceList = Arrays.asList("aoas", "ags", "asrc", "ascc", "asma");
        List<String> refreshServices = services.stream().filter(serviceId -> !exceptServiceList.contains(serviceId)).collect(Collectors.toList());
        for(String serviceId :refreshServices) {
            List<ServiceInstance> instances = client.getInstances(serviceId);
            //获取请求参数的url路径
            String url = "";
            for (ServiceInstance instance : instances) {
                // instance.getUri()+ 微服务模块路由前缀+path路径（每个公司不一样的）
                url = instance.getUri()+serviceId.split("-")[0].toLowerCase()+ path;
            }
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            // 请求用户，这里作为mybatis plus的自动填充表的字段数据
            headers.add("UserId", "admin");
            // 机构信息
            headers.add("OrgId", "org");
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(dept), headers);
            // post请求调参数
            String s = restTemplate.postForObject(url, formEntity, String.class);
            System.out.println(s);
        }

    }
}
